package com.mediacloud.app.newsmodule.fragment.album;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mediacloud.app.appfactory.cache.AppConfig;
import com.mediacloud.app.assembly.banner.NetImageBanner;
import com.mediacloud.app.assembly.banner.NetImageBanner4Component;
import com.mediacloud.app.assembly.banner.NetImageBannerX;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.fbnavsk.SecondNav;
import com.mediacloud.app.model.VideoPlay;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.PayTipsUtilsKt;
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.album.live.LiveAlbumNewsListAdaptor;
import com.mediacloud.app.newsmodule.fragment.BaseExpandListFragment;
import com.mediacloud.app.newsmodule.fragment.video.vod.PlayClickListener;
import com.mediacloud.app.newsmodule.fragment.video.vod.VideoListPlayerUtil;
import com.mediacloud.app.newsmodule.utils.CacheDataKt;
import com.mediacloud.app.newsmodule.utils.LBSRefreshLocation;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.newsmodule.utils.NewsListDataInvoker;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.reslib.enums.Navigate;
import com.mediacloud.app.reslib.util.DataInvokeUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 直播专辑列表
 *
 * @author x
 */
public class LiveAlbumListFragment extends BaseExpandListFragment<LiveAlbumNewsListAdaptor, List<String>, Map<String, List<ArticleItem>>, String, ArticleItem> implements NetImageBanner.OnItemClickListener, PlayClickListener {
    protected String catalogID;
    protected Bundle arguments = null;
    protected CatalogItem catalogItem;
    protected NewsListDataInvoker dataInvoker;
    protected BaseDataInvokeCallBack dataCallback;
    protected NetImageBanner4Component banner;
    protected List<ArticleItem> bannerData;
    protected int maxBannerSize;
    protected boolean haveBanner = false;
    protected boolean haveAddComponent31 = false;
    public static final String HAVE_BANNER = "1";
    public VideoListPlayerUtil mVideoListPlayerUtil;


    protected void initDataInvoker() {
        dataCallback = new BaseAlbumListDataInvokeCallBack();
        dataInvoker = new NewsListDataInvoker(dataCallback);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            arguments = savedInstanceState.getBundle(SaveArgs);
        }

        childGropData = new LinkedHashMap<String, List<ArticleItem>>();
        groupLabel = new ArrayList<String>();
        initDataInvoker();
    }

    @Override
    public void initView() {
        attached = false;
        isLoading = false;
        pageNum = 1;
        loadingView = findViewById(R.id.mLoadingView);
        initStateView();
        loadingView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showStateView(TYPE_LOADING, false);
                onRefresh();
            }
        });
        mCatalogContentItemListView = findViewById(R.id.mCatalogContentItemListView);

        mCatalogContentItemListView.setBackgroundResource(R.color.white);
        mCatalogContentItemListView.setOnGroupClickListener(new OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                return true;
            }
        });
        mCatalogContentItemListView.setOnChildClickListener(new OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                ArticleItem item = adaptor.getChild(groupPosition, childPosition);
                if (item != null) {
                    NewsItemClickUtils.OpenItemNewsHandle(getActivity(), item.getType(), item, catalogItem);
                }
                return false;
            }
        });
        mEmptyContent = findViewById(R.id.mEmptyContent);
        adaptor = new LiveAlbumNewsListAdaptor(getActivity());
        adaptor.setPlayClickListener(this);
        adaptor.setBaseExpandableListParents(groupLabel);
        adaptor.setBaseExpandableLisChilds(childGropData);
        if (getFragmentArguments() != null) {
            arguments = getFragmentArguments();
            catalogID = arguments.getString("id");
            catalogItem = arguments.getParcelable("catalog");
        } else if (arguments != null) {
            catalogID = arguments.getString("id");
            catalogItem = arguments.getParcelable("catalog");
        }
        adaptor.catalogItem = catalogItem;
        addLBSChosoeHeader(catalogItem);
        mCatalogContentItemListView.addHeaderView(headerViewContainer);
       // addBanner();
        componetContainer.componentListItemStyleAdaptor.catalogItem = catalogItem;
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        mCatalogContentItemListView.setAdapter(adaptor);
        mEmptyContent.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showStateView(TYPE_LOADING, false);
                onRefresh();
            }
        });
        setRefreshLayoutColor(refreshLayout, getNavigate());
    }

    @org.jetbrains.annotations.Nullable
    @Override
    public Navigate getNavigate() {
        if (catalogItem != null && catalogItem.getNavigate() != null)
            return catalogItem.getNavigate();
        return super.getNavigate();
    }

    protected void addBanner() {
        int extraStyle = this.catalogItem != null ? this.catalogItem.getCatalogStyle() : 0;
        if (extraStyle > 0 && HAVE_BANNER.equals(getActivity().getResources().getString(R.string.newslist_havebanner))) {
            haveBanner = false;
            return;
        }
        bannerData = new ArrayList<ArticleItem>();
        String bannerDefNum = AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()) != null ? AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getContent_list_banner() : "3";
        maxBannerSize = TextUtils.isEmpty(bannerDefNum) ? 3 : Integer.valueOf(bannerDefNum);
        banner = new NetImageBanner4Component(getActivity());
        //		banner.allowLoopTouch=false;
        int mainColor = Color.parseColor(AppFactoryGlobalConfig.getAppServerConfigInfo(getActivity()).getColor());
        banner.currentFocusItemColor = mainColor;
//		banner.defaultBackGroundResId= DefaultBgUtil.getDefaultImageBg(getActivity());
//		NetImageBanner.DefaultDelta=(float) (1.0/2.0f);
        headerViewContainer.addView(banner, 0);
        banner.dotContainer.setVisibility(View.VISIBLE);
        banner.currentImage.setVisibility(View.GONE);
        haveBanner = true;
        banner.setOnItemClickListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dataInvoker != null) {
            dataInvoker.destory();
            dataInvoker = null;
        }
        if (adaptor != null) {
            adaptor.destroy();
        }
        attached = false;
        if (componetContainer != null)
            componetContainer.dispose();
        componetContainer = null;
        if (mVideoListPlayerUtil != null)
            mVideoListPlayerUtil.onDestroy();
        mVideoListPlayerUtil=null;
    }



    boolean checkInited = false;

    @Override
    public void choosed() {
        super.choosed();
        if (getActivity() != null && !checkInited) {
            useCache();
          //  mRootView.postDelayed(() -> onRefresh(), 500);
        }
        EventBus.getDefault().post(new VideoPlay(true));
    }

    @Override
    public void unChosoed() {
        super.unChosoed();
        if (mVideoListPlayerUtil != null) {
            mVideoListPlayerUtil.stopPlay();
        }
        EventBus.getDefault().post(new VideoPlay(false));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (mVideoListPlayerUtil != null) {
                mVideoListPlayerUtil.stopPlay();
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser) {
            if (mVideoListPlayerUtil != null) {
                mVideoListPlayerUtil.stopPlay();
            }
        }
    }

    @Override
    public int getLayoutResID() {
        return R.layout.fragment_ablum_list;
    }

    @Override
    public void onRefresh() {
        attached = true;
        checkInited = true;
        AppConfig appConfig = new AppConfig(getActivity());
        boolean unkeep = appConfig.lbsIsAutoMode() && Utility.gpsIsOpen(getActivity());
        if (catalogItem != null && catalogItem.getLbsItem() != null && !isFirst && unkeep) {
            new LBSRefreshLocation(this).start(getActivity());
        } else {
            isFirst = false;
            doRefresh();
        }
    }

    boolean isFirst = true;
    @Override
    public final void doRefresh() {
        super.doRefresh();
        if (isLoading)
            return;
        isLoading = true;
        pageNum = 1;
        if (mCatalogContentItemListView != null) {
            //useCache();
            Log.w("APPTAG", "onFresh");
            getNewsListData();
        }
    }

    @Override
    public void useCache() {
        if (mCatalogContentItemListView != null) {
            ArticleListData dataResult = CacheDataKt.readData(this, catalogID, ArticleListData.class);
            if (adaptor != null && adaptor.getBaseExpandableLisChilds() != null && adaptor.getBaseExpandableLisChilds().size() == 0 && dataCallback != null && dataResult != null && dataResult.articleList.size() > 0) {
                Log.w("APPTAG", "useCache");
                dataCallback.success(dataResult);
            }else{
                onRefresh();
            }
        }
    }


    /**
     * 取新闻列表
     */
    protected void getNewsListData() {
        if (catalogItem != null && !TextUtils.isEmpty(catalogItem.getLbsNavigateDataId())) {
            catalogID = catalogItem.getLbsNavigateDataId();
        }
        int tempSize = 50;//改成和ios一样
        dataInvoker.getContentList(catalogID,pageNum,tempSize,null);
    }

    @Override
    public void onLoadMore() {
        if (isLoading)
            return;
        isLoading = true;
        pageNum++;
        getNewsListData();
    }

    @Override
    public void onPlayIcoClick(View rootView, ViewGroup container, View playIcon,final ArticleItem item) {
        if (mVideoListPlayerUtil == null) {
            mVideoListPlayerUtil = new VideoListPlayerUtil(getActivity(), mCatalogContentItemListView,this);
            mVideoListPlayerUtil.setHqyNavFragment(this);
            if(getParentFragment() instanceof SecondNav){
                mVideoListPlayerUtil.mPlayer.setViewPlayer(((SecondNav)getParentFragment() ).getViewPager());
            }
        }
        if (item!=null&&mVideoListPlayerUtil.item!=null&&mVideoListPlayerUtil.getPlayer()!=null
                &&mVideoListPlayerUtil.item.equals(item)&&mVideoListPlayerUtil.getPlayer().isPlaying()){
            return;
        }
        mVideoListPlayerUtil.setPlayerContainer(rootView, container,playIcon, !TextUtils.isEmpty(item.getGoodsID()), new OnClickListener() {
            @Override
            public void onClick(View v) {
                item.setParentId(catalogID);
                NewsItemClickUtils.OpenItemNewsHandle(getActivity(), item.getType(), item, catalogItem);
            }
        }, item);
        mVideoListPlayerUtil.setVideoDetail(catalogID + "", item);
    }

    /**
     * 如果存在31组件和banner时，就采用这种操作把这个31组件放到头部
     */
    private void addComponent31Header(ArticleListData result) {
        ComponentItem item = result.componentItems.remove(0);
        if (!haveAddComponent31) {
            try {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.component_type31, null);
                TextView bigTitleTv = view.findViewById(R.id.text_big_title);
                TextView smallTitleTv = view.findViewById(R.id.text_small_title);
                headerViewContainer.addView(view, 0);
                haveAddComponent31 = true;
                String element = item.element;
                final List<ArticleItem> articleItemList = JSON.parseArray(element, ArticleItem.class);
                if (articleItemList.size() != 0) {
                    bigTitleTv.setText(articleItemList.get(0).getTitle());
                    bigTitleTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //是否为大图样式，大图样式采用新的图集详情页
                            NewsItemClickUtils.OpenItemNewsHandle(getActivity(), articleItemList.get(0).getType(), articleItemList.get(0), new CatalogItem());
                        }
                    });
                }
                if (articleItemList.size() > 0) {
                    smallTitleTv.setText(articleItemList.get(1).getTitle());
                    smallTitleTv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            NewsItemClickUtils.OpenItemNewsHandle(getActivity(), articleItemList.get(1).getType(), articleItemList.get(1), new CatalogItem());
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public class BaseAlbumListDataInvokeCallBack extends BaseDataInvokeCallBack<ArticleListData> {
        @Override
        public void success(ArticleListData result) {
            if (adaptor == null)
                return;
            isLoading = false;
            Log.w("APPTAG", "success livealbum");
            if (pageNum == 1)
                CacheDataKt.saveData(LiveAlbumListFragment.this, catalogID, result.orginData + "");
            JSONObject data = result.orginData.optJSONObject("data");
            if (pageNum == 1) {
                if (FloatButtonGroup.haveFloatField(data)) {
                    initFloatWin(data);
                } else {
                    hideFloatWin();
                }
            }
            if (pageNum == 1) {
                refreshLayout.finishRefresh();
                if (adaptor.getBaseExpandableListParents() != null)
                    adaptor.getBaseExpandableListParents().clear();
                if (adaptor.getBaseExpandableLisChilds() != null)
                    adaptor.getBaseExpandableLisChilds().clear();
                //添加组件  用的HeadView
                //加一个31组件（两行文字的顶栏组件）的头部
                // (这里的逻辑是顶栏组件移动到头部，移除它在组件中的位置，保证它置顶)
                if (needAddComponent31(result.componentItems) && haveBanner) {
                    addComponent31Header(result);
                }
                componetContainer.updateComponent(result.componentItems);
                childGropData.clear();

                if (haveBanner && !needRemoveSelfBanner(result.componentItems))//有banner情况
                {
                    bannerData.clear();
                    int maxSize = result.articleList.size() >= maxBannerSize ? maxBannerSize : result.articleList.size();
                    for (int i = 0; i < maxSize; i++) {
                        bannerData.add(result.articleList.remove(0));
                    }
                    attached = true;
                    refreshBanner();
                } else if (banner != null) {
                    banner.defaultHeight = 0;
                    banner.cleanAll();
                    banner.updateLayout();
                }
            }
            groupLabel.clear();
            String label = null;
//			if(result.articleList.size()>0)
            {
                label = getResources().getString(R.string.livealbum_video);
                groupLabel.add(label);
                if (!childGropData.containsKey(label) || pageNum == 1)
                    childGropData.put(label, result.articleList);
                else
                    childGropData.get(label).addAll(result.articleList);
            }
            if (result.audioList.size() > 0) {
                label = getResources().getString(R.string.livealbum_audio);
                groupLabel.add(label);
                if (!childGropData.containsKey(label) || pageNum == 1) {
                    childGropData.put(label, result.audioList);
                } else
                    childGropData.get(label).addAll(result.audioList);
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                if (result.more)
                    refreshLayout.finishLoadMore();
                else
                    refreshLayout.finishLoadMoreWithNoMoreData();
//				mCatalogContentItemListView.setPullLoadEnable(result.more);
            }
            adaptor.setBaseExpandableListParents(groupLabel);
            adaptor.setBaseExpandableLisChilds(childGropData);
            adaptor.groupOpend = result.isOpenedGroup();
            adaptor.notifyDataSetChanged();
            closeStateView();
            if (childGropData.size() == 0 && result.componentItems.size() == 0) {
                showStateView(TYPE_NO_CONTENT, false);
            }
            for (int i = 0; i < adaptor.getGroupCount(); i++) {
                if (adaptor.getChildrenCount(i) > 0)
                    mCatalogContentItemListView.expandGroup(i);
            }
        }

        @Override
        public void fault(Object object) {
            super.fault(object);
            showStateView(TYPE_NET_NOT_GIVE_FORCE, false);
        }
    }

    protected void refreshBanner() {
        if (bannerData.size() == 0 || attached == false)
            return;
        banner.cleanAll();
        for (ArticleItem item : bannerData) {
            banner.addItem(item.getLogo(), PayTipsUtilsKt.payTips(item, getActivity(), getActivity().getResources().getString(R.string.pay_a_pei), getActivity().getResources().getDimension(R.dimen.pay_label_size), (int) getActivity().getResources().getDimension(R.dimen.pay_label_bgradius)), AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), item.getType());
        }
        int bannerHeight = (int) (getResources().getDisplayMetrics().widthPixels * banner.DefaultDelta);
        banner.defaultHeight = bannerHeight;
        banner.updateLayout();
    }

    @Override
    public void onClick(NetImageBanner banner, int position, Object tag) {
        ArticleItem item = bannerData.get(position);
        item.setParentId(catalogID);
        NewsItemClickUtils.OpenItemNewsHandle(getActivity(), item.getType(), item, catalogItem);
        if (mVideoListPlayerUtil != null) {
            mVideoListPlayerUtil.stopPlay();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("id", catalogID);
        outState.putParcelable("catalog", catalogItem);
        super.onSaveInstanceState(outState);
    }


}